package org.standard.sys.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.standard.sys.model.SysCode;
import org.standard.sys.model.SysLog;
import org.standard.commons.exception.InfrastructureException;
import org.standard.commons.utils.DAO;
import org.standard.commons.utils.DateUtil;
import org.standard.commons.utils.FlipPageInfo;
import org.standard.sys.service.SysLogService;

public class SysLogServiceImpl implements SysLogService {
	private final char SUCCESS = '1';// 操纵成功
	private final char FAIL = '0';// 操纵失败
	private DAO dao;

	public DAO getDao() {
		return dao;
	}

	public void setDao(DAO dao) {
		this.dao = dao;
	}

	/**
	 * 该方法返回：统计从日志开始记取到现在的总天数，日志记录总数，今年日志记记录总数，本月日志记记录总数，本日日志记记录总数，日志平均记录总数
	 * 
	 * @return list
	 * @author wang zitao
	 */
	public List summary() {
		List list = new ArrayList();
		Date current = new Date(); // 获得当前时间
		try {

			// 统计从日志开始记取到现在的总天数
			List templist = dao.find("select min(logTime) from SysLog");
			Date date = (Date) templist.get(0);
			Integer totleDay = 0;
			if (date != null)
				totleDay = DateUtil.beforeDays(date, current)+1;//把相邻的日期算做一天
			list.add(totleDay);

			// 统计从日志开始记取到现在的总记录数
			templist = dao.find("select count(logId) as totle from SysLog");
			Integer totleRecord = (Integer) templist.get(0);
			list.add(totleRecord);

			// 统计今年日志记记录总数
			Integer year = DateUtil.getYear(current); // 获得当前年份
			templist = dao
					.find("select count(logId) as totle from SysLog where YEAR(logTime)='"
							+ year + "'");
			Integer yearRecord = (Integer) templist.get(0);
			list.add(yearRecord);

			// 统计本月日志记录总数
			Integer month = DateUtil.getMonth(current); // 获得当前月份
			templist = dao.find("select count(logId) as totle from SysLog where YEAR(logTime)=? and MONTH(logTime)=? ",
							new Object[] { year, month });
			Integer monthRecord = (Integer) templist.get(0);
			list.add(monthRecord);

			// 统计本日日志记录总数
			Integer day = DateUtil.getDay(current); // 获得当前日期
			templist = dao.find(
					"select count(logId) as totle from SysLog where YEAR(logTime)=? and "
							+ " MONTH(logTime)=? and DAY(logTime)=?",
					new Object[] { year, month, day });
			Integer dayRecord = (Integer) templist.get(0);
			list.add(dayRecord);

			// 统计日志平均记录总数
			Integer averRecord = 0;
			if (0 != totleDay)
				averRecord = Math.round(totleRecord / totleDay);
			list.add(averRecord);
			return list;
		} catch (InfrastructureException e) {
			return new ArrayList();
		}
	}

	/**
	 * 该方法统计最近n条日志记录
	 * 
	 * @param 传入page对象
	 * @return 日志记录
	 * @author wang zitao
	 * 
	 */
	public FlipPageInfo recentRecord(FlipPageInfo fpi) {
		// 查询TOP n条记录，以时间时间排序
		String hql="select user.userName,log.logTime,log.logIp,code.codeName,log.logContent from SysLog log,SysCode code," +
				"BaseUser user where log.codeNo=code.codeNo and code.codeNoParent='SYS_LOG' and log.userId =user.userId order by log.logTime desc ";
		FlipPageInfo fpis = dao.findWithPaging(hql, fpi);
		if (fpis.getData()!=null)
			return fpis;
		else
			return new FlipPageInfo();
	}
	private String userId;
	private Date logTime;
	private String logIp;
	private String codeNo;
	private String logContent;
	
	
	/**
	 * 该方法用于查找某个用户最近的10条记录
	  * @param 传入page对象,用户Id
	 * @return 日志记录
	 * @author wang zitao
	 */
	public FlipPageInfo recentRecord(FlipPageInfo fpi,String userId) {
		// 查询TOP n条记录，以时间时间排序
		String hql="select code.codeName,log.logTime,log.logIp,log.logContent from SysLog log,SysCode code " +
				"where log.codeNo=code.codeNo and code.codeNoParent='SYS_LOG' and log.userId ='"+userId+"' order by log.logTime desc ";
		FlipPageInfo fpis = dao.findWithPaging(hql, fpi);
		if (fpis.getData()!=null)
			return fpis;
		else
			return new FlipPageInfo();
	}

	/**
	 * 该方法用于查找日志类型 *
	 * 
	 * @return 所有系统日志类型
	 * @author wang zitao
	 * 
	 */
	public List<SysCode> searchLogType() {
		List<SysCode> templist = dao
				.find("from SysCode where codeNoParent = 'SYS_LOG'");
		if (templist.size() > 0)
			return templist;
		else
			return new ArrayList();
	}
 
	/**
	 * 该方法用于查找日志查询
	 * 
	 * @param logType
	 *            日志类型
	 * @param startTime开始时间
	 * @param endTime结束时间
	 * @param LogIp
	 *            IP地址
	 * @return 分页对象
	 * @author wang zitao
	 * 
	 */
	public FlipPageInfo searchLog(FlipPageInfo fpi,String codeNo, Date startTime, Date endTime,
			String logIp) {
		StringBuffer hql = new StringBuffer();
		List params = new ArrayList();
		FlipPageInfo fpis;
		if ("-1".equals(codeNo)) {// 查询所有所有类型的符合条件的日志
			hql.append("select user.userName,log.logTime,log.logIp,code.codeName,log.logContent,log.logId from SysLog log,SysCode code," +
						"BaseUser user where log.codeNo=code.codeNo and code.codeNoParent='SYS_LOG' and log.userId =user.userId ");
			if (startTime != null && !"".equals(startTime))// 判断开始时间是否为空
			{
				hql.append(" and log.logTime>?");
				params.add(startTime);
			}
			if (endTime != null && !"".equals(endTime))// 判断结束时间是否为空
			{
				hql.append(" and log.logTime<?");
				params.add(endTime);
			}
			if (logIp != null && !"".equals(logIp))// 判断访问Ip是否为空
			{
				hql.append(" and log.logIp=?");
				params.add(logIp);
			}
		} else {
			hql.append("select user.userName,log.logTime,log.logIp,code.codeName,log.logContent,log.logId from SysLog log,SysCode code," +
					"BaseUser user where log.codeNo=code.codeNo and code.codeNoParent='SYS_LOG' and log.userId =user.userId and code.codeNo = ?");
			params.add(codeNo);
			if (startTime != null && !"".equals(startTime))// 判断开始时间是否为空
			{
				hql.append(" and log.logTime>?");
				params.add(startTime);
			}
			if (endTime != null && !"".equals(endTime))// 判断结束时间是否为空
			{
				hql.append(" and log.logTime<?");
				params.add(endTime);
			}
			if (logIp != null && !"".equals(logIp))// 判断访问Ip是否为空
			{
				hql.append(" and log.logIp=?");
				params.add(logIp);
			}
		}
		hql.append(" order by log.logTime desc ");
		if (params.size() == 0)// 如果没有参数的话，按此方法查询
			fpis = dao.findWithPaging(hql.toString(), fpi);
		else if (params.size() == 1)// 如果只有一个参数的话，按此方法查询
			fpis = dao.findWithPaging(hql.toString(), fpi,params.get(0));
		else
			fpis = dao.findWithPaging(hql.toString(), fpi,params.toArray());
		if (fpis.getData()!=null)
			return fpis;
		else
			return new FlipPageInfo();
	}

	/**
	 * 该方法用于删除符合条件的日志
	 * 
	 * @param logType
	 *            日志类型
	 * @param startTime开始时间
	 * @param endTime结束时间
	 * @param LogIp
	 *            IP地址
	 * @return 删除所有符合条件的系统日志
	 * @author wang zitao
	 * 
	 */
	public char deleteLog(String codeNo, Date startTime, Date endTime,
			String logIp) {
		StringBuffer hql = new StringBuffer();
		List params = new ArrayList();
		if ("-1".equals(codeNo)) {// 删除所有类型的符合条件的日志
			hql.append("delete from SysLog  where 1=1");
			if (startTime != null && !"".equals(startTime))// 判断开始时间是否为空
			{
				hql.append(" and logTime>?");
				params.add(startTime);
			}
			if (endTime != null && !"".equals(endTime))// 判断结束时间是否为空
			{
				hql.append(" and logTime<?");
				params.add(endTime);
			}
			if (logIp != null && !"".equals(logIp))// 判断访问Ip是否为空
			{
				hql.append(" and logIp=?");
				params.add(logIp);
			}
		} else {
			hql
					.append("delete  from SysLog where codeNo= ?");
			params.add(codeNo);
			if (startTime != null && !"".equals(startTime))// 判断开始时间是否为空
			{
				hql.append(" and logTime>?");
				params.add(startTime);
			}
			if (endTime != null && !"".equals(endTime))// 判断结束时间是否为空
			{
				hql.append(" and logTime<?");
				params.add(endTime);
			}
			if (logIp != null && !"".equals(logIp))// 判断访问Ip是否为空
			{
				hql.append(" and logIp=?)");
				params.add(logIp);
			}
		}
		hql.append("");
		if (params.size() == 0)// 如果没有参数的话，按此方法删除
		{
			try {
				int i = dao.updateBulk(hql.toString());
				return SUCCESS;
			} catch (InfrastructureException e) {
				return FAIL;
			}
		} else if (params.size() == 1)// 如果只有一个参数的话，按此方法删除
		{
			try {
				int i = dao.updateBulk(hql.toString(), params.get(0));
				return SUCCESS;
			} catch (InfrastructureException e) {
				return FAIL;
			}
		} else {
			try {
				int i = dao.updateBulk(hql.toString(), params.toArray());
				return SUCCESS;
			} catch (InfrastructureException e) {
				return FAIL;
			}
		}

	}

	/**
	 * 该方法用于清空所有系统日志 *
	 * 
	 * @return 清空是否成功
	 * @author wang zitao
	 * 
	 */
	public char deleteAllLog() {
		try {
			int i = dao.updateBulk("delete from SysLog where 1=1");
			return SUCCESS;
		} catch (InfrastructureException e) {
			return FAIL;
		}
	}
	
	
	
	/**
	 * 该方法用于删除所选的系统日志 *
	 * @param sellog 所选logId
	 * @return S=0 成功；s=1失败
	 * @author wang zitao
	 * 
	 */
	public char deleteLog(String[] sellog){
		try{
		if(null!=sellog&&sellog.length>0)
			for(String id:sellog){
			dao.delete(SysLog.class,id);
			}
		return SUCCESS;
		}catch(Exception e){
			return FAIL;
		}

	}
	
	
	
}